package com.fd.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        System.out.println("LoginFilter.doFilter+++++=>"+ requestURI);
        //下面方法表示当前拦截通过

        HttpServletResponse resp=(HttpServletResponse)response;
        //判断如果是登录页面,或者是登录请求,不用拦截,
//        requestURI.contains("log333in.jsp")
        if (requestURI.contains("login.jsp") || requestURI.contains("userAdd")) {
            //直接放行
            chain.doFilter(request, response);
            //如果不是登录页面,或者登录请求
        } else {
            //先检查是否在session有登录信息
            HttpSession session = httpRequest.getSession();
            Object loginUser = session.getAttribute("loginUser");
//            如果没有登录信息,说明用户没有登录,直接重定向到登录页面
            if (loginUser == null) {
                resp.sendRedirect("login.jsp");
                return;
            }
            //如果在session存在loginUser,那么直接放行
            chain.doFilter(request, response);
        }

    }
}
